<?php
// +----------------------------------------------------------------------
// | 奇乐中介担保交易系统 免费版 2019
// +----------------------------------------------------------------------
// | 官方网址：http://www.qilecms.com   
// +----------------------------------------------------------------------
// | 产品文档：http://www.qilecms.com/doc
// +----------------------------------------------------------------------
// | 开发作者:奇乐CMS
// +----------------------------------------------------------------------
// | 版权说明：这不是一个自由软件！本产品仅限个人使用，但请务必保留底部版权，以免产生不必要的纠纷,
// | 您只能在不用于商业目的的前提下对程序代码进行修改和使用，
// | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
// +----------------------------------------------------------------------
namespace app\guarantee\controller;
use app\common\model\User;
use app\common\controller;
class Trade  extends Base
{
    public function index()
    {
      $param = $this->request->param();
      $keywords = !empty($param['keywords'])?$param['keywords']:'';
      $price    = !empty($param['p'])?$param['p']:''; //价格
      $cid      = !empty($param['c'])?$param['c']:''; //分类
      $status   = !empty($param['s'])?$param['s']:''; //状态
      $id_type   = !empty($param['i'])?$param['i']:''; //发布者身份
      $order_price  = !empty($param['op'])?$param['op']:'';
      if(!empty($keywords)){
       $where[] =['title','like',"%$keywords%"] ;

      }
      //分类
       if(!empty($cid)){
         $where[] =['cid','=',$cid];   
       }
      // 价格
       if(!empty($price)){
        switch($price)
        {
          case 1:
           $where[] =['price','<','1000'];
          break;
          case 2:
             $where[] =['price','between',['1000','5000']];
          break;
          case 3:
              $where[] =['price','between',['5000','10000']];
          break;
          case 4:
              $where[] =['price','between',['10000','50000']];
          break;
          case 5:
              $where[] =['price','between',['50000','100000']];
          break;
          case 6:
              $where[] =['price','between',['100000','200000']];
          break;
          case 7:
              $where[] =['price','>','200000'];
          break;
        }        
      }
    //交易状态
    if(!empty($status)){
         $where[] =['status','=',$status];   
       }


  //排序
      if($order_price ==1){
        $order_price =2;
        $order['price'] ='asc';  //价格从小到大
      }elseif($order_price ==2){
        $order_price =1;
        $order['price'] ='desc';  //价格从大到小
      }else{
        $order_price =1;

      }

      $order['create_time'] ='desc';  //价格从大到小
      $this->assign('order_price',$order_price);


      $cate = $this->getCache('guaranteeCategory','cid');
      $this->assign('guaranteecategory',$cate);
  //审核状态
     $where[] =['status','in',[1,2]];  //已审核 已交易 交易完成 

     $urlParam['keywords'] = $keywords;
     $urlParam['p'] = $price;
     $urlParam['s'] = $status;
     $urlParam['c'] = $cid;
     $urlParam['i'] = $id_type;
     $urlParam['op'] = $order_price;
     $list =  model('guaranteeInfo')->listPageData($where,'*',$order,'10,false,$urlParam');
    
     foreach($list as $k=>$v){
          $where1['cid'] = $v['cid'];
          $where1['status'] = 1;
          $list[$k]['cname'] = $cate[$v['cid']]['cname'];
     }

     

     $page = $list->render();
     $this->assign('page',$page);


     $empty = '<div class="empty">暂时没有数据</div>';
     $this->assign('empty',$empty);
     $this->assign('list',$list);
     return $this->fetch();
    }
//交易信息详情
  public function detail()
  {
    $param = $this->request->param();
    if(empty($param['id'])){
      return $this->error('当前交易信息不存在，或者已被删除！');
    }
 

    $id = intval($param['id']);
    $where['id']       = $id;
    $guaranteeInfo     = model('guaranteeInfo')->infoData($where);

    if($guaranteeInfo['status'] < 1 && $guaranteeInfo['uid'] != session('uid')){
     return $this->error('当前交易信息不存在，或者已被删除！');
    }
    $guaranteeCategory = $this->getCache('guaranteeCategory','cid');
    $guaranteeInfo['cname'] = $guaranteeCategory[$guaranteeInfo['cid']]['cname'];

//交易发布者信息
    $where2['uid'] = $guaranteeInfo['uid'];
    $userinfo = model('user')->infoData($where2);
    $guaranteeInfo['userinfo'] = $userinfo;  //用户



//更新点击量
    model('guaranteeInfo')->where(['id'=>$id])->setInc('hits',1);

//获得平台经纪人qq号码
   $agent = $this->settings['guarantee']['agent_qq'];
   $arr = explode("\n",$agent);
   $agent_qq= [];
   foreach($arr as $k=>$v){
      $two = explode('|',$v);
      $agent_qq[$k]['name'] = $two[0];
      $agent_qq[$k]['qq'] = $two[1];
   }
    $this->assign('agent_qq',$agent_qq);


   //订单
     $map['info_id'] = $id;
     $map['order_status'] = 1;
     $order = model('guarantee')->infoData($map);


     $guaranteeInfo['order'] =$order;



    $this->assign('guaranteeInfo',$guaranteeInfo);
    return $this->fetch();

  }


//发布交易信息
    public function publish()
    {
       $this->isLogin(); //判断是否登陆
       $this->isValidate(); //验证是否需要资质认证

        //判断qq是否填写
     if(empty($this->user['qq'])){
          $this->error('请在我的资料中填写您的常用QQ','/user/set/index');
      }

      if($this->request->isAjax()){
      	$param = $this->request->param();
      	
    //验证请求参数
        $rule =[
          'cid' =>'require|integer',
          'title'  =>'require|max:25',
          'price'  =>'require',
          'id_type'  =>'require|integer',
          'fee_type'  =>'require|integer',
        ];
        $msg= [
         'cid.require'  =>'请选择完整分类',
         'cid.integer'  =>'请选择正确的分类',
         'title.require'  =>'标题不能为空',
         'title.max' =>'信息标题最大25个字符',
         'price.require'      =>'请填写预期价格', 
         'id_type.require'      =>'请选择身份',
         'id_type.integer'      =>'请选择正确的身份',
         'fee_type.require'      =>'请选择手续费支付方式',
         'fee_type.integer'      =>'请选择正确的中介费支付方式', 
    
        ];
         $error = $this->checkSubmit($param,$rule,$msg);  
       if($error){
              return error_json($error);
         }
       
      if(empty($param['price']) || !is_numeric($param['price'])){
          return error_json('请填写逾期价格');    
        } 
        if($param['price'] < 1){
          return error_json('预期价格至少1元');    
        }  
        $data['cid']        = $param['cid'];
        $data['title']      = $param['title'];
        $data['uid']        = session('uid');
        $data['username']   = session('username');
        $data['id_type']    = $param['id_type'];
        $data['fee_type']   = $param['fee_type'];
        $data['price']      = $param['price'];
        $data['content']    = $param['content'];
        $data['create_time']    = time();

        if($this->settings['guarantee']['is_audit_info'] ==1){
        	//开启审核
           $data['status']  =1;
        }else{
           $data['status']  =0;
        }
        model('guaranteeInfo')->addData($data);
        return success_json('交易信息已发布');
      }else{
       

   
         return $this->fetch();      
      }

    }

//发起交易
    public function create()
    {

       $this->isLogin(); //判断是否登陆
       $this->isValidate(); //验证是否需要资质认证

       //判断qq是否填写
       if(empty($this->user['qq'])){
              $this->error('请在我的资料中填写您的常用QQ','/user/set/index');
       }
    
      	$param = $this->request->param();
      if($this->request->isAjax()){
      
    //验证请求参数
        $rule =[
          'cid' =>'require|integer',
          'title' =>'require',
          'username'  =>'require',
          'price'  =>'require',
          'id_type'  =>'require|integer',
          'fee_type'  =>'require|integer',
        ];
        $msg= [
         'cid.require'  =>'请选择完整分类',
         'cid.integer'  =>'请选择正确的分类',
         'title.require'  =>'交易标题不能为空',
         'title.chsAlpha' =>'交易标题只能是汉字或字母',
         'username.require'   =>'请输入对方用户名',
         'price.require'      =>'请输入交易价格', 
         'id_type.require'      =>'请选择身份',
         'id_type.integer'      =>'请选择正确的身份',
         'fee_type.require'      =>'请选择手续费支付方式',
         'fee_type.integer'      =>'请选择正确的手续费支付方式',    
        ];
         $error = $this->checkSubmit($param,$rule,$msg);  
       if($error){
              return error_json($error);
         }

         if(empty($param['price']) || !is_numeric($param['price'])){
          return error_json('请填写正确的交易价格');    
        }
        if($param['price'] < 1){
          return error_json('交易价格至少1元');    
        }  
        $username = addslashes($param['username']);
        $where['username'] =$username;
        $userinfo = model('user')->infoData($where);


        if($param['id_type'] == 0){
           //买家
          $data['buyer_uid']  = session('uid');
          $data['buyer']      = session('username');
          $data['seller_uid'] = $userinfo['uid'];
          $data['seller']     = $userinfo['username'];

        }elseif($param['id_type'] == 1){
           //卖家
           
          $data['buyer_uid']  = $userinfo['uid'];
          $data['buyer']      = $userinfo['username'];
          $data['seller_uid'] = session('uid');
          $data['seller']     = session('username');
          $data['order_status']     = 1;
        }
     //判断交易对象是否为自己
        if($username == session('username')){
          return error_json('发起对象不能是自己');
        }
        $where['username'] = $username;
        $user = model('user')->infoData($where);
        if(empty($user)){
          return error_json('对方用户名不存在');
        }
        if(!empty($param['id'])){
         //判断信息ID是否存在
          $data['info_id']    = intval($param['id']);  
        }
   

            //判断用户没有确认的订单是否过多,最多5条
            $uid = session('uid');
            $order_map[]    = ['order_status','IN',[0,1]];  //没有确认的订单
            $order_map[]      = ['pay_status','=',0];
            $order_map[] = ['shipping_status','=',0];
            $order_where = "buyer_uid = $uid Or seller_uid = $uid";
            $num = model('guarantee')->where($order_map)->where($order_where)->count();
            if($num >=5){
              return error_json('您提交的订单数量超过限制');
            }

        $data['cid']        = $param['cid'];
        
        $data['title']      = $param['title'];
        $data['fee_type']   = $param['fee_type']; //手续费支付方式
        $data['price']      = $param['price'];
        $data['fee_ratio']       = !empty($this->settings['guarantee']['fee_ratio'])?$this->settings['guarantee']['fee_ratio']:0; //手续费,0或者空 免手续费
        $data['buyer_pay']  = $param['buyer_pay'];  //买家获得
        $data['seller_get'] = $param['seller_get']; //卖家获得
        $data['fee_ratio']  = $this->settings['guarantee']['fee_ratio'];
        $data['content']    = $param['content'];
        $data['create_time']    = time(); 
        $obj  = model('guarantee')->addData($data);


        $returnData['url'] =url('trade/order',['id'=>$obj->id]);
        return success_json('交易创建成功',$returnData);


      }else{
    
      	if(!empty($param['id'])){
        

                //判断用户没有确认的订单是否过多,最多5条
                $uid = session('uid');
                $order_map[]    = ['order_status','IN',[0,1]];  //没有确认的订单
                $order_map[]      = ['pay_status','=',0];
                $order_map[] = ['shipping_status','=',0];
                $order_where = "buyer_uid = $uid Or seller_uid = $uid";
                $num = model('guarantee')->where($order_map)->where($order_where)->count();
                if($num >=5){
                  return $this->error('您提交的订单数量超过限制');
                }

          $map['id'] = intval($param['id']);

          $guaranteeInfo = model('guaranteeInfo')->infoData($map);
         
         // 获得信息发布者
		      $map3['uid'] = $guaranteeInfo['uid'];
		      $user = model('user')->infoData($map3);
		      $guaranteeInfo['username'] = $user['username'];

		      $this->assign('guaranteeInfo',$guaranteeInfo);
      	}
         
        
         return $this->fetch();      
      }

    }

  public function order()
  {
    $this->isLogin(); //判断是否登陆
    $param = $this->request->param();
    $step = !empty($param['step'])?intval($param['step']):0;
    $id   = !empty($param['id'])?intval($param['id']):'';
    if(!$param['id']){
       return $this->error('订单不存在');
    }
  
     //判断qq是否填写
   if(empty($this->user['qq'])){
          $this->error('请在我的资料中填写您的常用QQ','/user/set/index');
    }

    $id = intval($param['id']);


    $map['id'] = $id;
    $guaranteeData = model('guarantee')->infoData($map);
    //查询改订单是否有维权记录
    
    $rights = model('guaranteeRights')->infoData(['order_id'=>$guaranteeData['id']]);
    $guaranteeData['rights'] = $rights;
    

     
// 判断当前用户是否等于买家或者卖家
   if($this->user->uid != $guaranteeData['buyer_uid'] && $this->user->uid != $guaranteeData['seller_uid']){
       $this->redirect('/');
    }

    //获得对方信息
    if($guaranteeData['order_status'] ==0 && $guaranteeData['pay_status'] ==0 && $guaranteeData['shipping_status'] ==0){
   //等待确认  
      if($param['step'] !=  2){ 

        $this->redirect('trade/order',['step'=>2,'id'=>$id]);

      }
         $this->assign('title','等待确认');
    }elseif($guaranteeData['order_status'] ==1 && $guaranteeData['pay_status'] ==0 && $guaranteeData['shipping_status'] ==0){
      //等待买家付款
       if($param['step'] !=  3){ 
        $this->redirect('trade/order',['step'=>3,'id'=>$id]);
       }
       $this->assign('title','等待买家付款');
    }elseif($guaranteeData['order_status'] ==1 && $guaranteeData['pay_status'] ==1 && $guaranteeData['shipping_status'] ==0){
      //卖家发货 
        if($param['step'] !=  4){ 
              $this->redirect('trade/order',['step'=>4,'id'=>$id]);
            }
       $this->assign('title','卖家发货');
    }elseif($guaranteeData['order_status'] ==1 && $guaranteeData['pay_status'] ==1 && $guaranteeData['shipping_status'] ==1){
     //买家确认   
       if($param['step'] !=  5){ 
            $this->redirect('trade/order',['step'=>5,'id'=>$id]);
          }
         $this->assign('title','买家确认');
    }elseif($guaranteeData['order_status'] ==1 && $guaranteeData['pay_status'] ==1 && $guaranteeData['shipping_status'] ==2){
      //双方评价  
        if($param['step'] !=  6){ 
              $this->redirect('trade/order',['step'=>6,'id'=>$id]);
            }
          $this->assign('title','双方评价');
    }elseif($guaranteeData['order_status'] ==2 && $guaranteeData['pay_status'] ==0 && $guaranteeData['shipping_status'] ==0){
       //订单关闭
       $this->error('订单已经关闭！');

    }


    if(session('username') == $guaranteeData['buyer']){
      //卖家
       $map2['username'] = $guaranteeData['seller'];
       $role = 1;   //我的角色
    }elseif(session('username') == $guaranteeData['seller']){
      //买家
       $map2['username'] = $guaranteeData['buyer'];
       $role = 0;   //我的角色  
    }

    //获得买家信息
     $buyer = model('user')->infoData(['uid'=>$guaranteeData['buyer_uid']]);
     $guaranteeData['buyer_info'] = $buyer;
     
 
// 买家总收入
     $where3[] = ['uid','=',$guaranteeData['buyer_uid']];
     $where3[] = ['amount','>',0];
     $buyer_income =  model('financeRecord')->cache(3600)->where($where3)->sum('amount');
      $this->assign('buyer_income',$buyer_income); 


//获得卖家信息
     $seller = model('user')->infoData(['uid'=>$guaranteeData['seller_uid']]);
     $guaranteeData['seller_info'] = $seller;
    
//卖家总收入
     $where4[] = ['uid','=',$guaranteeData['seller_uid']];
     $where4[] = ['amount','>',0];
     $seller_income =  model('financeRecord')->cache(3600)->where($where4)->sum('amount');
      $this->assign('seller_income',$seller_income); 

     $this->assign('guaranteeData',$guaranteeData);

     return $this->fetch();
  } 




}
